package com.itheima.reggie.service.impl;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired(required = false)
    private ShoppingCartMapper shoppingCartMapper;
    /**
     * 添加购物车
     *
     * @param shoppingCart
     * @return
     */
    @Transactional
    @Override
    public R<ShoppingCart> addShoppingCart(ShoppingCart shoppingCart) {
        //处理数据
        shoppingCart.setCreateTime(LocalDateTime.now());
        if (shoppingCart.getNumber() == null){
            shoppingCart.setNumber(1);
        }
        //查询购物车中是否有完全相同记录。如果有只在原来基础上加一
        ShoppingCart dbShoppingCart = shoppingCartMapper.findSameshoppingCart(shoppingCart);
        if (dbShoppingCart!=null){
            dbShoppingCart.setNumber(dbShoppingCart.getNumber()+shoppingCart.getNumber());
            //只加数量
            if(shoppingCartMapper.updateShoppingCart(dbShoppingCart)>0){
                return R.success(dbShoppingCart);
            }else {
                return R.error("添加失败");
            }

        }
        //如果没有，则新增数据
        return shoppingCartMapper.insertShoppingCart(shoppingCart) > 0 ? R.success(shoppingCart):R.error("添加失败");
    }

    /**
     * 购物车减数量
     *
     * @param shoppingCart
     */
    @Transactional
    @Override
    public R<ShoppingCart> subShoppingCart(ShoppingCart shoppingCart) {
        ShoppingCart dbShoppingCart = shoppingCartMapper.findSameshoppingCart(shoppingCart);
        Integer number = dbShoppingCart.getNumber();
        if ( number == 1){
            shoppingCartMapper.delete(dbShoppingCart);
            dbShoppingCart.setNumber(0);
            //删除
            return R.success(dbShoppingCart);
        }else {
            dbShoppingCart.setNumber(number - 1);
            return shoppingCartMapper.updateShoppingCart(dbShoppingCart) >0 ? R.success(dbShoppingCart):R.error("失败");
        }

    }

    /**
     * 查询购物车列表
     *
     * @param id
     * @return
     */
    @Override
    public R<List<ShoppingCart>> findShoppingCartByUserId(Long id) {
        List<ShoppingCart> shoppingCartList= shoppingCartMapper.findShoppingCartByUserId(id);
        return R.success(shoppingCartList);
    }

    /**
     * 清空购物车
     *
     * @param userId
     * @return
     */
    @Override
    public int cleanShoppingCart(Long userId) {
        return shoppingCartMapper.cleanShoppingCart(userId);
    }
}
